import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index'
// 创建路由实例 createRouter
const router = createRouter({
  // 模式 hash history
  // history: createWebHistory(), 地址栏不带#
  // hash: createWebHashHistory(), 地址栏带#
  // vite 中的环境变量.meta.env.BASE_URL
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录页面
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue')
    },
    // 默认架构页面
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      // 默认路由
      redirect: '/articale/manage',
      // 子路由
      children: [
        {
          path: '/articale/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        }
      ]
    }
  ]
})
// 登录访问拦截
// 默认直接放行跳转
// 根据返回值判断是否拦截
// 返回 undefined/true 放行
// 返回 false 拦截form的地址
// 返回具体路径或路径对象，拦截到对应地址
router.beforeEach(async (to) => {
  const userStore = useUserStore()
  // 没有token,且访问非登录页面，进行拦截
  if (!userStore.token && to.path !== '/login') return '/login'
})
export default router
